package com.shmn.gongjiajumain.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shmn.gongjiajumain.service.JigFamilyService;
import com.shmn.gongjiajumain.service.WorkcellService;
import com.shmn.gongjiajumain.vo.jig.JigDetailVo;
import com.shmn.gongjiajumain.vo.jig.JigTableVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shmn.common.utils.PageUtils;
import com.shmn.common.utils.Query;

import com.shmn.gongjiajumain.dao.JigDefinitionDao;
import com.shmn.gongjiajumain.entity.JigDefinitionEntity;
import com.shmn.gongjiajumain.service.JigDefinitionService;

@Slf4j
@Service("jigDefinitionService")
public class JigDefinitionServiceImpl extends ServiceImpl<JigDefinitionDao, JigDefinitionEntity> implements JigDefinitionService {

    @Autowired
    private JigFamilyService jigFamilyService;

    @Autowired
    private WorkcellService workcellService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Map<String, Object> dataForm = new HashMap<>();
        if (params.containsKey("dataForm")) {
            String dataFormStr = (String) params.get("dataForm");
            try {
                dataForm = new ObjectMapper().readValue(dataFormStr, new TypeReference<Map<String, Object>>() {
                });
            } catch (Exception e) {
                log.error("Failed to parse dataForm parameter: {}", dataFormStr);
            }
        }
        String family = (String) dataForm.get("family");
        String workcell = (String) dataForm.get("workcell");
        List<Integer> familyIds = jigFamilyService.getIdByFam(family);
        List<Integer> workcellIds = workcellService.getIdByWorkcell(workcell);

// 根据解析出来的参数进行模糊查询
        QueryWrapper<JigDefinitionEntity> queryWrapper = new QueryWrapper<JigDefinitionEntity>()
                .like(StringUtils.isNotBlank((String) dataForm.get("name")), "name", dataForm.get("name"))
                .like(StringUtils.isNotBlank((String) dataForm.get("userFor")), "user_for", dataForm.get("userFor"));

        if (!CollectionUtils.isEmpty(workcellIds)) {
            queryWrapper.in("workcell_id", workcellIds.toArray(new Integer[0]));
        }

        if (!CollectionUtils.isEmpty(familyIds)) {
            queryWrapper.in("family_id", familyIds.toArray(new Integer[0]));
        }

        IPage<JigDefinitionEntity> page = this.page(
                new Query<JigDefinitionEntity>().getPage(params),
                queryWrapper
        );
        PageUtils pageUtil = new PageUtils(page);
        List<JigTableVo> list = new ArrayList<>();
        Class<JigDefinitionEntity> clazz = JigDefinitionEntity.class;
        pageUtil.getList().forEach(item -> {
            JigTableVo jigTableVo = new JigTableVo();
            BeanUtils.copyProperties(item, jigTableVo);
            Integer familyId = null;
            Integer workcellId = null;
            try {
                Field field = clazz.getDeclaredField("familyId");
                Field field1 = clazz.getDeclaredField("workcellId");
                field.setAccessible(true);
                field1.setAccessible(true);
                familyId = (Integer) field.get(item);
                workcellId = (Integer) field1.get(item);
            } catch (Exception e) {
                log.error("错误:{}", e.getMessage());
            }
//            System.out.println("Workcellid" + workcellId);
            jigTableVo.setFamily(jigFamilyService.getById(familyId).getFamily());
            jigTableVo.setWorkcell(workcellService.getById(workcellId).getWorkcell());
            jigTableVo.setStockCount(new Random().nextInt(10));
            list.add(jigTableVo);
        });
        pageUtil.setList(list);
        return pageUtil;
    }

    @Override
    public JigDetailVo getByInfoId(Integer id) {
        System.out.println("-----"+id);
        JigDefinitionEntity jigDefinitionEntity = baseMapper.selectById(id);
        JigDetailVo jigDetailVo = new JigDetailVo();
        BeanUtils.copyProperties(jigDefinitionEntity, jigDetailVo);
        jigDetailVo.setFamily(jigFamilyService.getById(jigDefinitionEntity.getFamilyId()).getFamily());
        jigDetailVo.setWorkcell(workcellService.getById(jigDefinitionEntity.getWorkcellId()).getWorkcell());
        return jigDetailVo;
    }


//    @Override
//    public PageUtils queryPage1(JigDetailVo jigDetailVo) {
//        /**
//         * 条件查询+分页
//         */
//
//        Map<String, Object> params = new HashMap<>();
//        params.put("page",jigDetailVo.getPageIndex());
//        params.put("limit",jigDetailVo.getPageSize());
//        params.put("key",jigDetailVo.getKey());
//
//        QueryWrapper<JigDefinitionEntity> wrapper = new QueryWrapper<>();
//        if (jigDetailVo.getCode() != null){
//            wrapper.like("code",jigDetailVo.getCode());
//        }
//
//        IPage<JigDefinitionEntity> page = this.page(
//                new Query<JigDefinitionEntity>().getPage(params),
//                wrapper
//        );
//
//        /**
//         * 构建并返回vo对象
//         */
//
//        PageUtils pageUtils = new PageUtils(page);
//        List<JigDetailVo> purchaseIncomeTableVos = new ArrayList<>();
//        Class<PurchaseIncomeSubmitEntity> clazz = PurchaseIncomeSubmitEntity.class;
//        pageUtils.getList().forEach(item->{
//            JigDetailVo jigDetailVo = new PurchaseIncomeTableVo();
//            BeanUtils.copyProperties(item,purchaseIncomeTableVo);
//            String submitId = null;
//            Integer productionLineId = null;
//            String code = null;
//            String count = null;
//            Date submitTime = null;
//            try {
//                Field field1 = clazz.getDeclaredField("submitId");
//                Field field2 = clazz.getDeclaredField("productionLineId");
//                Field field3 = clazz.getDeclaredField("code");
//                Field field4 = clazz.getDeclaredField("count");
//                Field field5 = clazz.getDeclaredField("submitTime");
//                field1.setAccessible(true);
//                field2.setAccessible(true);
//                field3.setAccessible(true);
//                field4.setAccessible(true);
//                field5.setAccessible(true);
//                submitId = (String)field1.get(item);
//                productionLineId =(Integer) field2.get(item);
//                code = (String) field3.get(item);
//                count = (String) field4.get(item);
//                submitTime = (Date) field5.get(item);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            String codeAndCount = getCodeAndCount(code, count);
//            UserEntity user = userService.getById(submitId);
//            ProductionLineEntity productionLine = productionLineService.getById(productionLineId);
//            purchaseIncomeTableVo.setSubmitTime(DateUtil.formatDate(submitTime));
//            purchaseIncomeTableVo.setSubmitName(user.getName());
//            purchaseIncomeTableVo.setProductionLine(productionLine.getWorkcell());
//            purchaseIncomeTableVo.setCodeAndCount(codeAndCount);
//            purchaseIncomeTableVos.add(purchaseIncomeTableVo);
//        });
//        pageUtils.setList(purchaseIncomeTableVos);
//        return pageUtils;
//    }

}